package com.blueocean_health.care.management.interceptor;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 去除参数空格
 * @version 1.0
 * @date 2018年01月30 17:33
 * @description
 */
@ControllerAdvice(basePackages = "com.blueocean_health")
public class RemoveSpaceControllerAdvice extends RequestBodyAdviceAdapter{
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
    	Class<? extends Object> clazz = body.getClass();
        List<Field> fields = new ArrayList<>();
        getAllFields(clazz,fields);
//        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object object = field.get(body);
                if (object instanceof String){
                    String value = object.toString().trim();
//                    System.out.println("~~~~~~~~~"+value);
                    field.set(body, value);
                }
            } catch (Exception e) {
            }
        }
        return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
    }

    private void getAllFields(Class<?> clazz, List<Field> fields) {
        if (clazz != Object.class){
            Field[] fs = clazz.getDeclaredFields();
            fields.addAll(Arrays.asList(fs));
            getAllFields(clazz.getSuperclass(),fields);
        }
    }
}
